<!--
 * @Author: Li Zengkun
 * @Date: 2022-09-11 16:45:23
 * @LastEditors: Li Zengkun
 * @LastEditTime: 2022-09-16 16:52:07
 * @Description: 
-->
<template>
  <el-image class="avatar" :src="imageUrl"></el-image>
  <br />
  <div style="width: 100%; margin-top: 10px">
    <el-button
      icon="Search"
      type="primary"
      style="margin-bottom: 10px"
      @click="isBigShow = true"
      >{{ props.dataType === "avatar" ? "浏览头像" : "浏览封面" }}</el-button
    >
    <el-upload
      ref="upload"
      v-model:file-list="fileList"
      class="upload-demo"
      action="http://localhost:3001/upload/common/"
      :headers="headers"
      :limit="1"
      :data="data"
      accept=".jpg,.png,.jpeg"
      multiple
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :before-remove="beforeRemove"
      :on-exceed="handleExceed"
      :auto-upload="false"
    >
      <template #trigger> </template>
      <el-button icon="Folder" type="success" @click="openSelector">{{
        props.dataType === "avatar" ? "选择头像" : "选择封面"
      }}</el-button>
      <template #tip>
        <div class="el-upload__tip">
          jpg/png files with a size less than 500KB.
        </div>
      </template>
    </el-upload>
  </div>

  <el-dialog v-model="isBigShow" title="图片浏览">
    <el-image
      style="width: 100%; text-align: center"
      :src="imageUrl"
    ></el-image>
  </el-dialog>

  <el-dialog ref="dialog" :width="600" v-model="isDialogShow" title="图片裁剪">
    <ImgCutter
      ref="ImgCutterRef"
      :isModal="false"
      v-on:cutDown="cutDown"
      :boxWidth="560"
      label="选择图片"
      :rate="rate"
      :WatermarkText="WatermarkText"
    >
    </ImgCutter>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, reactive, onMounted, nextTick } from "vue";
import ImgCutter from "vue-img-cutter";
import { upload } from "@/api";
import { ElMessage } from "element-plus";

const uploadRef = ref(null);
const dialog = ref(null);

let isBigShow = ref(false);
const isDialogShow = ref(false);

const props = defineProps({
  modelValue: String,
  dataType: {
    type: String,
    required: true,
    default: "common",
  },
});

const rate = props.dataType === "avatar" ? "1:1" : "16:9";

const WatermarkText = props.dataType === "avatar" ? "" : "水印测试";

const emit = defineEmits(["update:modelValue"]);

const ImgCutterRef = ref(null);

const handlePreview = () => {
  console.log("handlePreview");
};
const handleRemove = () => {
  console.log("handleRemove");
};
// const handleChange = ()=>{
//   console.log("handleChange");
// }
const beforeRemove = () => {
  console.log("beforeRemove");
};
const openSelector = async () => {
  isDialogShow.value = true;
  await nextTick();
  ImgCutterRef.value.chooseImg();
};
const beforeUpload = async (rawFile) => {
  // var fReader = new FileReader();
  // fReader.readAsDataURL(rawFile);
  // imageUrl.value = fReader.result;
  // console.log(fReader);
  // let imgSrc = file.getAsDataURL();
  let imgSrc = window.URL.createObjectURL(rawFile);
  isDialogShow.value = true;
  await nextTick();
  console.log(ImgCutterRef);
  let obj = {
    name: rawFile.name,
    src: imgSrc,
  };
  console.log(ImgCutterRef);
  ImgCutterRef.value.handleOpen(obj);
  console.log(imgSrc);
  console.log("beforeUpload");
  return false;
};

// 初始化预览图
const imageUrl = ref(props.modelValue);

const initImg = (obj) => {
  console.log(obj);
};

// 参数
const data = {
  type: props.dataType,
};

// 图片上传url侦听
watch(imageUrl, (newValue, oldValue) => {
  emit("update:modelValue", newValue);
});

/**
 * @description: 返回响应时执行的方法
 * @return {*}
 * @param {*} response 响应
 * @param {*} uploadFile 上传的文件
 */
const handleAvatarSuccess = (response, uploadFile) => {
  // 上传成功
  if (response.status) {
    imageUrl.value = response.src;
    ElMessage({
      type: "success",
      message: response.msg,
    });
  }
  // 上传失败
  else {
    ElMessage({
      type: "error",
      message: "上传图片失败",
    });
  }
};

/**
 * @description: 发出请求之前的处理
 * @return {*}
 * @param {*} rawFile 选择的文件
 */
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile.type);
  if (!/^image\/(jpeg|png|jpg)$/.test(rawFile.type)) {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

const cutDown = async (testImg) => {
  console.log(testImg);
  if (beforeAvatarUpload(testImg.file)) {
    imageUrl.value = testImg.dataURL;
    testImg.file.url = testImg.dataURL;
    let data = {
      file: testImg.file,
      type: props.dataType,
    };
    let { status, msg, src } = await upload.common(data);
    if (status) {
      imageUrl.value = src;
      ElMessage.success(msg);
    } else {
      ElMessage.error(msg);
    }
    isDialogShow.value = false;
  }
};
</script>

<style lang="less" scoped>
.avatar {
  min-width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    overflow: hidden;
  }
  .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
